<template>
  <div class="chat-msg">
    <div class="chat-title">{{name}}</div>
    <message-list class="chat-msg-list" :data="msg" />
    <editor @send="handleSend" @change="handlChange" :value="content" />
  </div>
</template>
<script>
import storage from 'good-storage'
import { CURRENT_CHAT_KEY, USER_KEY, getMsgListKey } from '@/assets/js/constant'
import MessageList from '@/components/messageList/messageList.vue'
import Editor from '@/components/Base/Form/Editor.vue'
import { getChatMsgList } from '@/service'
export default {
  name: 'ChatMsg',
  components: { MessageList, Editor },
  props: {
    data: Object
  },
  data() {
    return {
      msg: [],
      content: ''
    }
  },
  async created() {
    const data = this.computedData
    if (!data) {
      const path = this.$route.matched[0].path
      this.$router.push({
        path
      })
    }
    // this.getData(data.groupId)
  },
  methods: {
    async getData(groupId) {
      // 请求数据 **code
      const KEY = getMsgListKey(groupId)
      const msg = storage.session.get(KEY) || await getChatMsgList({ groupId })
      this.msg = msg
      this.cache(msg, groupId)
    },
    handlChange(content) {
      this.content = content
    },
    handleSend(content) {
      // 发送信息 code
      const id = this.msg.length + 1
      const userId = storage.session.get(USER_KEY).userId
      this.msg.push({
        id: id,
        userId: userId,
        content: content
      })
      // 发送成功 code
      this.content = ''
      this.cache(this.msg)
    },
    cache(list, id) {
      const groupId = id || this.computedData.groupId
      const KEY = getMsgListKey(groupId)
      storage.session.set(KEY, list)
    }
  },
  computed: {
    computedData() {
      let ret = null
      const data = this.data
      if (data) {
        ret = data
      } else {
        const cached = storage.session.get(CURRENT_CHAT_KEY)
        if (cached && (cached.groupId || cached.id + '') === this.$route.params.id) {
          ret = cached
        }
      }
      if (ret && ret.groupId) {
        this.getData(ret.groupId)
      }
      return ret
    },
    name() {
      const data = this.computedData
      return (data && data.name) || ''
    }
  }
}
</script>
<style lang="scss" scoped>
.chat {
  &-msg {
    font-size: 15px;
    color: $color-text-b;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow: hidden;
  }
  &-title {
    height: 32px;
    line-height: 32px;
    letter-spacing: 2px;
    background-color: $color-background-l;
    text-align: center;
  }
  &-msg-list {
    flex: 1;
  }
}
.editor-wrapper {
  // border-top: 1px solid $color-background-l;
  background-color: $color-background-l;
}
</style>
